package com.lx.controller;

import com.jcraft.jsch.SftpException;
import com.lx.entity.Product;
import com.lx.service.ProductService;
import com.lx.service.RedisService;
import com.lx.util.PageInfo;
import com.lx.util.Result;
import com.lx.util.SftpUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.Map;
import java.util.UUID;

@RestController
@RequestMapping("/api")
@Api(tags = "商品管理接口")
public class ProductController {

    @Autowired
    private ProductService productService;
    @Autowired
    private RedisService redisService;
    @Value("${sftp.username}")
    private String username;
    @Value("${sftp.password}")
    private String password;
    @Value("${sftp.host}")
    private String host;
    @Value("${sftp.port}")
    private Integer port;
    @Value("${sftp.imagePath}")
    private String imagePath;


    /**
     * 分页查询商品列表（ES搜索）
     */
    @PostMapping("/product/pageinfo")
    @ApiOperation(value = "分页查询商品列表", notes = "支持名称和创建时间搜索")
    public Result getPageInfo(@RequestBody Map<String, Object> params) {
        if (params.containsKey("name") && (params.get("name") == null || params.get("name").toString().isEmpty())) {
            params.remove("name");
        }
        if (params.containsKey("createTime") && (params.get("createTime") == null || params.get("createTime").toString().isEmpty())) {
            params.remove("createTime");
        }
        PageInfo<Product> pageInfo = productService.getPageInfo(params);
        return Result.success(5200, "获取搜索商品列表成功").add("pageinfo", pageInfo);
    }
    /**
     * 分页查询商品列表，该分页主要用于通过分类连接点进去，不需要高亮显示，且查询条件为{categoryId, type}
     */
    @PostMapping("/product/category")
    @ApiOperation(value = "分页查询商品列表", notes = "仅支持相关类别搜索")
    public Result getPageInfoByCategory(@RequestBody Map<String, Object> params) {
        PageInfo<Product> pageInfo = productService.getPageInfoByCategory(params);
        return Result.success(5200, "获取分类下的商品列表成功").add("pageinfo", pageInfo);
    }

    /**
     * 添加商品
     */
    /*@CheckPermission("1")
    @PostMapping("/product/add")
    @ApiOperation(value = "添加商品", notes = "添加新商品")
    public Result addProduct(@RequestBody Product product) {
        boolean result = productService.addProduct(product);
        if (result) {
            return Result.success(5200, "添加成功");
        }
        return Result.error(5500, "添加失败");
    }*/

    /**
     * 修改商品
     */
    @PostMapping("/product/update0")
    @ApiOperation(value = "修改商品", notes = "修改商品信息")
    public Result updateProduct0(@RequestBody Product product) {
        boolean result = productService.updateProduct(product);
        if (result) {
            return Result.success(5200, "修改成功");
        }
        return Result.error(5500, "修改失败");
    }
    @PostMapping("/product/update")
    @ApiOperation(value = "修改商品", notes = "修改商品信息")
    public Result updateProduct(MultipartFile newImg,
                                Product product) {
        //判断是否修改了文件
        if(newImg != null && !newImg.isEmpty()) {
            //删除旧图片
            String newFilename = null;
            SftpUtil sftp = new SftpUtil(username, password, host, port);
            try{
                //登录
                sftp.login();
                String filename = newImg.getOriginalFilename();
                String end = filename.substring(filename.lastIndexOf('.') + 1);
                newFilename = UUID.randomUUID() + "." + end;
                //输出到服务器特定目录, 源文件转换成输入流
                sftp.upload(imagePath, newFilename, newImg.getInputStream());
                //删除旧图
                /*if(!product.getFileName().isEmpty()) {
                    sftp.delete(imagePath, product.getFileName()); //删除imagePath文件夹下的该文件
                }*/
                //安全删除旧图
                if(product.getFileName() != null && !product.getFileName().isEmpty()) {
                    try {
                        sftp.delete(imagePath, product.getFileName());
                        System.out.println("旧图片已删除: " + product.getFileName());
                    } catch (SftpException e) {
                        // 检查是否是"文件不存在"的错误 (错误代码 2)
                        if (e.id == 2) { // SSH_FX_NO_SUCH_FILE
                            System.out.println("旧图片不存在，无需删除: " + product.getFileName());
                        } else {
                            // 其他SFTP错误，记录警告但不影响主流程
                            System.out.println("删除旧图片时发生错误: " + e.getMessage());
                        }
                    }
                }
                product.setFileName(newFilename);

            } catch (SftpException e) {
                throw new RuntimeException(e);
            } catch (IOException e) {
                throw new RuntimeException(e);
            } finally {
                sftp.logout();
            }
        }
        //其他正常执行
        boolean result = productService.updateProduct(product);
        if (result) {
            return Result.success(5200, "修改成功");
        }
        return Result.error(5500, "修改失败");
    }

    /**
     * 删除商品
     */
    @PostMapping("/product/delete")
    @ApiOperation(value = "删除商品", notes = "逻辑删除商品")
    public Result deleteProduct(@RequestBody Map<String, Object> params) {
        Integer id = Integer.parseInt(params.get("id").toString());
        boolean result = productService.deleteProduct(id);
        if (result) {
            return Result.success(5200, "删除成功");
        }
        return Result.error(5500, "删除失败");
    }

    /**
     * 获取商品详情
     */
    @PostMapping("/product/detail")
    @ApiOperation(value = "获取商品详情", notes = "根据ID获取商品详情")
    public Result getProductById(@RequestBody Map<String, Object> params) {
        Integer id = Integer.parseInt(params.get("id").toString());
        Product product = productService.getProductById(id);
        if (product != null) {
            return Result.success(5200, "获取成功").add("product", product);
        }
        return Result.error(5500, "未找到商品");
    }

    /**
     ** 商品新增，图片上传到远程服务器niginx上
     */
    @PostMapping("/product/add")
    public Result addProduct(@RequestParam("image")MultipartFile imageFile,
                              Product product) {
        if(imageFile == null) return Result.error(5500, "商品图片不能为空！");
        String newFilename = null;
        SftpUtil sftp = new SftpUtil(username, password, host, port);
        try{
            //登录
            sftp.login();
            String filename = imageFile.getOriginalFilename();
            String end = filename.substring(filename.lastIndexOf('.') + 1);
            newFilename = UUID.randomUUID() + "." + end;
            //输出到服务器特定目录, 源文件转换成输入流
            sftp.upload(imagePath, newFilename, imageFile.getInputStream());
            product.setFileName(newFilename);
            //新增商品
            productService.addProduct(product);
            return Result.success(5200, "新增商品成功！");
        } catch (SftpException e) {
            throw new RuntimeException(e);
        } catch (IOException e) {
            throw new RuntimeException(e);
        } finally {
            sftp.logout();
        }

    }



}
